#include "server_core.h"
#include <QJsonDocument>
#include <QJsonObject>
#include <QDebug>
#include"message_util.h"
#include<QJsonArray>
#include"user.h"
#include<windows.h>
ServerCore::ServerCore(ServerNetwork *network, QObject *parent)
    : QObject(parent), network(network),userDb(nullptr)
{
    // 连接网络层的原始数据信号到业务处理槽
    connect(network, &ServerNetwork::rawDataReceived, this, &ServerCore::handleRawData);

    connect(network, &ServerNetwork::clientDisconnected, this, &ServerCore::handleClientDisconnected);
    dbConnection.connect("localhost", "chat_server", "root", "123456");
    userDb=new UserDatabase(&dbConnection);
    friendDb=new FriendDatabase(&dbConnection);
    groupDb=new GroupDatabase(&dbConnection);
    User user1(1,"qi");
    User user2(2,"fu");
    User user3(3,"da");
    allUser.append(user1);
    allUser.append(user2);
    allUser.append(user3);

}

void ServerCore::handleClientDisconnected(QTcpSocket *socket) {
    // 遍历 userToSocket，找到对应的用户名并移除
    QString usernameToRemove;
    for (auto it = userToSocket.begin(); it != userToSocket.end(); ++it) {
        if (it.value() == socket) {
            usernameToRemove = it.key();
            break;
        }
    }
    if (!usernameToRemove.isEmpty()) {
        userToSocket.remove(usernameToRemove);

        // 从 allUser 列表中移除用户
        for (int i = 0; i < allUser.size(); ++i) {
            if (allUser[i].getUsername() == usernameToRemove) {
                allUser.removeAt(i);
                break;
            }
        }
        qDebug() << "User" << usernameToRemove << "removed due to disconnection";
    }

    QJsonObject response;
    response["sender"] = "Server";
    response["success"] = true;
    QJsonArray jsonArray;
    for (const User &user : allUser) {
        jsonArray.append(user.toJson());
    }
    response["allUser"]=jsonArray;
    response["online"]=allUser.size();
    for(const User &user : allUser){
        if(userToSocket.contains(user.getUsername())){
            QTcpSocket *receiverSocket = userToSocket[user.getUsername()];
            if (receiverSocket && receiverSocket->state() == QAbstractSocket::ConnectedState) {
                network->sendDataToClient(receiverSocket, message.serialize(ONLINE_USERS_UPDATE, response));
            } else {
                qDebug() << "Socket for user" << user.getUsername() << "is invalid, skipping";
            }
        }
    }
}

// 公共确认方法
void ServerCore::sendTransferAck(QTcpSocket *socket, const QString &fileName, bool success,
                                 MessageType responseType, const QString &errorMsg) {
    QJsonObject ack;
    ack["success"] = success;
    ack["fileName"] = fileName;
    if (!errorMsg.isEmpty()) ack["remsg"] = errorMsg;
    network->sendDataToClient(socket, message.serialize(responseType, ack));
}

// 图片格式验证工具函数
bool ServerCore::isValidImageFormat(const QString &fileName) {
    QStringList allowedFormats = {"png", "jpg", "jpeg", "gif", "bmp"};
    QString suffix = fileName.split(".").last().toLower();
    return allowedFormats.contains(suffix);
}

bool ServerCore::verifyUser(const QString &username, const QString &password){
    return userDb->verifyLogin(username,password);
}

bool ServerCore::RegisterUser(const QString &username,const QString &password){
    return userDb->Register(username,password);
}

// 处理原始数据（业务逻辑入口）
void ServerCore::handleRawData(QTcpSocket *socket, const QByteArray &data) {
    qDebug() << "Received raw data from client, size:" << data.size();
    qDebug() <<data;
    // 1. 解析消息（业务逻辑）
    MessageType type;
    QJsonObject dataVal;
    bool m=message.deserialize(data,type,dataVal);
    //qDebug()<<dataVal;
    qDebug()<<type<<m;
    switch (type) {
    case LOGIN_REQUEST:
    {
        int userId=userDb->verifyLogin(dataVal["username"].toString(),dataVal["password"].toString());

        QJsonObject json;
        json["userId"]=userId;
        json["success"]=userId!=-1;
        json["remsg"]=userId!=-1 ? "Login success" : "Invalid credentials";
        network->sendDataToClient(socket,message.serialize(LOGIN_RESPONSE,json));
        // 3. 维护用户映射（业务逻辑）
        if (userId!=-1) {
            userToSocket[dataVal["username"].toString()] = socket;
            User user(userId,dataVal["username"].toString());
            allUser.append(user);
            Sleep(1000);
            QJsonObject response;
            response["sender"] = "Server";
            response["success"] = true;
            QJsonArray jsonArray;
            for (const User &user : allUser) {
                jsonArray.append(user.toJson());
            }
            response["allUser"]=jsonArray;
            response["online"]=allUser.size();
            for(const User &user : allUser){
                if(userToSocket.contains(user.getUsername())){
                    QTcpSocket *receiverSocket = userToSocket[user.getUsername()];
                    if (receiverSocket && receiverSocket->state() == QAbstractSocket::ConnectedState) {
                        network->sendDataToClient(receiverSocket, message.serialize(ONLINE_USERS_UPDATE, response));
                    } else {
                        qDebug() << "Socket for user" << user.getUsername() << "is invalid, skipping";
                    }
                }
            }
            qDebug() << "User" << dataVal["username"].toString() << "logged in, socket mapped";
        }
        break;
    }
    case REGISTER_REQUEST:
    {
        bool isValid=RegisterUser(dataVal["username"].toString(),dataVal["password"].toString());

        QJsonObject json;
        json["success"]=isValid;
        json["remsg"]=isValid ? "Register success" : "Invalid credentials";
        network->sendDataToClient(socket,message.serialize(REGISTER_RESPONSE,json));
        break;
    }
    case PRIVATE_CHAT:
    {
        if(userToSocket.contains(dataVal["receiver"].toString())){
            QTcpSocket *receiverSocket = userToSocket[dataVal["receiver"].toString()];
            // QJsonObject receive;
            // receive["sender"]=dataVal["sender"].toString();
            // receive["receiver"]=dataVal["receiver"].toString();
            // receive["content"]=dataVal["content"].toString();
            qDebug()<<dataVal;
            network->sendDataToClient(receiverSocket,message.serialize(PRIVATE_CHAT,dataVal));
        }else {
            qDebug()<<"error";
        }
        break;
    }
    case ADD_FRIEND:
    {
        qDebug()<<"add friend";
        bool isValid=friendDb->addFriend(userDb->getIdByName(dataVal["sender"].toString()),userDb->getIdByName(dataVal["receiver"].toString()));
        QJsonObject response;
        response["success"]=isValid;
        network->sendDataToClient(socket,message.serialize(ADD_FRIEND,response));
        break;
    }
    case REMOVE_FRIEND:
    {
        bool isValid=friendDb->removeFriend(userDb->getIdByName(dataVal["sender"].toString()),userDb->getIdByName(dataVal["receiver"].toString()));
        QJsonObject response;
        response["success"]=isValid;
        network->sendDataToClient(socket,message.serialize(REMOVE_FRIEND,response));
        break;
    }
    case CREATE_GROUP:
    {
        int isValid=groupDb->createGroup(dataVal["groupName"].toString(),dataVal["senderId"].toInt());
        QJsonObject response;
        response["suceess"]=isValid!=-1?true:false;
        response["groupId"]=isValid;
        network->sendDataToClient(socket,message.serialize(CREATE_GROUP,response));
        break;
    }
    case ADD_GROUP_MEMBER:
    {
        int groupId = dataVal["groupId"].toInt();
        int memberId = userDb->getIdByName(dataVal["memberUsername"].toString());
        bool isValid = groupDb->addGroupMember(groupId, memberId);
        QJsonObject response;
        response["success"] = isValid;
        network->sendDataToClient(socket, message.serialize(ADD_GROUP_MEMBER, response));
        break;
    }
    case REMOVE_GROUP_MEMBER:
    {
        int groupId = dataVal["groupId"].toInt();
        int memberId = userDb->getIdByName(dataVal["memberUsername"].toString());
        bool isValid = groupDb->removeGroupMember(groupId, memberId);
        QJsonObject response;
        response["success"] = isValid;
        network->sendDataToClient(socket, message.serialize(REMOVE_GROUP_MEMBER, response));
        break;
    }
    case SEND_GROUP_MESSAGE:
    {
        // int groupId = dataVal["groupId"].toInt();
        // QString senderUsername = dataVal["sender"].toString();
        // QString messageText = dataVal["text"].toString();

        // // 假设 groupDb 有一个方法可以获取群组成员的用户 ID 列表
        // QList<int> memberIds = groupDb->getGroupMembers(groupId);
        // for (int memberId : memberIds) {
        //     QString memberUsername = userDb->getNameById(memberId);
        //     if (userToSocket.contains(memberUsername) && memberUsername != senderUsername) {
        //         QTcpSocket *receiverSocket = userToSocket[memberUsername];
        //         QJsonObject receive;
        //         receive["sender"] = senderUsername;
        //         receive["groupId"] = groupId;
        //         receive["text"] = messageText;
        //         network->sendDataToClient(receiverSocket, message.serialize(SEND_GROUP_MESSAGE, receive));
        //     }
        // }


        QJsonObject response;
        QString sender = dataVal["sender"].toString();
        response["success"] = true;
        response["content"]=dataVal["content"].toString();
        for(const User &user : allUser){
            if(user.getUsername()!=sender&&userToSocket.contains(user.getUsername())){
                QTcpSocket *receiverSocket = userToSocket[user.getUsername()];
                network->sendDataToClient(receiverSocket, message.serialize(GROUP_CHAT, dataVal));
            }
        }

        break;
    }
    case GET_GROUP_MESSAGES:
    {
        int groupId = dataVal["groupId"].toInt();
        // 假设 groupDb 有一个方法可以获取群组的消息列表
        QList<QJsonObject> messages = groupDb->getGroupMessages(groupId);
        QJsonObject response;
        QJsonArray messagesArray;

        // 遍历消息列表，逐个添加到数组
        for (const QJsonObject& msg : messages) {
            messagesArray.append(msg);
        }

        response["messages"] = messagesArray;
        //response["messages"] = QJsonArray::fromVariantList(messages.toVector().toList());
        network->sendDataToClient(socket, message.serialize(GET_GROUP_MESSAGES, response));
        break;
    }
    case GET_FRIENDS_LIST:
    {
        QString sender = dataVal["sender"].toString();
        int senderId = userDb->getIdByName(sender);
        if (senderId == -1) {
            // 未找到该用户，返回错误消息
            QJsonObject response;
            response["id"] = dataVal["id"];
            response["sender"] = "Server";
            response["receiver"] = sender;
            response["success"] = false;
            response["remsg"] = "User not found.";
            network->sendDataToClient(socket, message.serialize(GET_FRIENDS_LIST, response));
            break;
        }

        // 获取好友列表
        QList<QJsonObject> friendsList = friendDb->getFriendsList(senderId);

        // 构建响应消息
        QJsonObject response;
        response["userId"] = dataVal["userId"].toInt();
        response["sender"] = "Server";
        response["receiver"] = sender;
        response["success"] = false;
        QJsonArray friendsJsonArray;
        for (const auto& friendObj : friendsList) {
            friendsJsonArray.append(friendObj);
        }
        response["friendsList"] = friendsJsonArray;

        // 将响应消息转换为 JSON 并发送给客户端
        network->sendDataToClient(socket, message.serialize(GET_FRIENDS_LIST, response));
        break;
    }
    case ONLINE_USERS_UPDATE:
    {
        QJsonObject response;
        response["sender"] = "Server";
        response["receiver"] = dataVal["sender"].toString();
        response["success"] = true;
        QJsonArray jsonArray;
        for (const User &user : allUser) {
            jsonArray.append(user.toJson());
        }
        response["allUser"]=jsonArray;
        network->sendDataToClient(socket, message.serialize(ONLINE_USERS_UPDATE, response));
    }
    case IMAGE_TRANSFER: {
        QString sender = dataVal["sender"].toString();
        QString receiver = dataVal["receiver"].toString();
        QString fileName = dataVal["fileName"].toString();
        QByteArray imageData = QByteArray::fromBase64(dataVal["fileData"].toString().toUtf8());

        // 验证图片格式（示例：检查后缀名）
        if (!isValidImageFormat(fileName)) {
            QJsonObject error;
            error["success"] = false;
            error["remsg"] = "Unsupported image format";
            network->sendDataToClient(socket, message.serialize(IMAGE_TRANSFER_RESPONSE, error));
            break;
        }
        if(receiver=="所有人"){
            for(const User &user : allUser){
                if(user.getUsername()!=sender&&userToSocket.contains(user.getUsername())){
                    QTcpSocket *receiverSocket = userToSocket[user.getUsername()];
                    network->sendDataToClient(receiverSocket, message.serialize(IMAGE_TRANSFER, dataVal));
                }
            }
            break;
        }else{
            if (userToSocket.contains(receiver)) {
                QTcpSocket *receiverSocket = userToSocket[receiver];
                network->sendDataToClient(receiverSocket, message.serialize(IMAGE_TRANSFER, dataVal));
                //sendTransferAck(socket, fileName, true, IMAGE_TRANSFER_RESPONSE); // 发送确认
            } else {
                sendTransferAck(socket, fileName, false, IMAGE_TRANSFER_RESPONSE, "Receiver offline");
            }
            break;
        }
        // 转发逻辑

    }

        // 文件传输独立处理
    case FILE_TRANSFER: {
        QString sender = dataVal["sender"].toString();
        QString receiver = dataVal["receiver"].toString();
        QString fileName = dataVal["fileName"].toString();
        QByteArray fileData = QByteArray::fromBase64(dataVal["fileData"].toString().toUtf8());

        // 验证文件大小（示例：限制为10MB）
        if (fileData.size() > 10 * 1024 * 1024) {
            QJsonObject error;
            error["success"] = false;
            error["remsg"] = "File exceeds size limit";
            network->sendDataToClient(socket, message.serialize(FILE_TRANSFER_RESPONSE, error));
            break;
        }

        // 转发逻辑
        if(receiver=="所有人"){
            for(const User &user : allUser){
                if(user.getUsername()!=sender&&userToSocket.contains(user.getUsername())){
                    QTcpSocket *receiverSocket = userToSocket[user.getUsername()];
                    network->sendDataToClient(receiverSocket, message.serialize(FILE_TRANSFER, dataVal));
                }
            }
            break;
        }else{
            if (userToSocket.contains(receiver)) {
                QTcpSocket *receiverSocket = userToSocket[receiver];
                network->sendDataToClient(receiverSocket, message.serialize(FILE_TRANSFER, dataVal));
                //sendTransferAck(socket, fileName, true, IMAGE_TRANSFER_RESPONSE); // 发送确认
            } else {
                sendTransferAck(socket, fileName, false, FILE_TRANSFER, "Receiver offline");
            }
            break;
        }

        if (userToSocket.contains(receiver)) {
            QTcpSocket *receiverSocket = userToSocket[receiver];
            network->sendDataToClient(receiverSocket, message.serialize(FILE_TRANSFER, dataVal));
            //sendTransferAck(socket, fileName, true, FILE_TRANSFER_RESPONSE);
        } else {
            sendTransferAck(socket, fileName, false, FILE_TRANSFER_RESPONSE, "Receiver offline");
        }
        break;
    }
    default:
        qDebug()<<"error";
        break;
    }
}

